<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="88px">
      <el-form-item label="权益卡名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入权益卡名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="渠道" prop="channel" v-hasPermi="['wx:qyk:type']">
        <el-select v-model="queryParams.channel" placeholder="请选择渠道" clearable size="small">
          <el-option
            v-for="item in channelOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="微信客户端" prop="wxClientId">
        <el-input
          v-model="queryParams.wxClientId"
          placeholder="请输入微信客户端"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wx:qyk:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wx:qyk:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx:qyk:remove']"
        >删除</el-button>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExportDetail"
            v-hasPermi="['wx:qykDetail:export']"
          >导出</el-button>
        </el-col>
      </el-col>
      <el-col :span="1.5"  v-hasPermi="['wx:qyk:count']">
        <span>已使用次数：{{ count.used?count.used:0 }}</span>
        <span>未使用次数：{{ count.unUsed?count.unUsed:0 }}</span>
        <span>过期次数：{{ count.overtime?count.overtime:0 }}</span>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="qykList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="权益卡名称" align="center" prop="name" />
      <el-table-column label="原价" align="center" prop="originalPrice" />
      <el-table-column label="售价" align="center" prop="price" />
      <el-table-column label="购买人数" align="center" prop="buyNum" >
        <template slot-scope="scope">
          <span @click="showUser(scope.row)" style="cursor: pointer;">{{ scope.row.buyNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道" align="center" prop="channel"  :formatter="channelFormat"/>
      <el-table-column label="过期时间" align="center" prop="expiration" v-has-permi="['wx:qyk:overtime']" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span :class="'verifyStatus_'+scope.row.status">{{statusFormat(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
<!--      <el-table-column label="微信客户端" align="center" prop="wxClientId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wx:qyk:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx:qyk:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改权益卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="98px">
        <el-form-item label="权益卡名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权益卡名称" />
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input v-model="form.originalPrice" type="number" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="form.price" type="number" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="渠道" prop="channel" v-hasPermi="['wx:qyk:type']">
          <el-select v-model="form.channel" placeholder="请选择渠道" style="width: 100%;" :disabled="form.id>0">
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="expiration" v-has-permi="['wx:qyk:overtime']">
            <el-date-picker
              v-model="form.expiration"
              type="datetime"
              :clearable="false"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="截止时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="优惠券" prop="couponIds" v-has-permi="['wx:qyk:coupon']">
          <el-select v-model="form.couponIds"  placeholder="请选择优惠券" clearable multiple style="width: 100%;" @change="couponIdsChange">
            <el-option
              v-for="item in couponInfoList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权益项" prop="qyxIds">
          <el-select v-model="form.qyxIds" placeholder="请选择权益项" clearable multiple style="width: 100%;" @change="qyxIdsChange">
            <el-option
              v-for="item in qyxList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-table :data="qyxIdsList" >
          <el-table-column label="权益项" align="center" prop="qyxName" />
          <el-table-column label="权益次数" align="center" prop="num" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.num" type="number" placeholder="请输入权益次数" />
            </template>
          </el-table-column>
        </el-table>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="submitForm" :disabled="buttonLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--展示购买用户 -->
    <el-dialog title="用户列表" :visible.sync="userShow" width="500px" append-to-body>
      <el-table :data="userList">
        <el-table-column label="姓名" align="center" prop="realName"/>
        <el-table-column label="昵称" align="center" prop="nickName"/>
        <el-table-column label="电话" align="center" prop="phone"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listSnpQyk,listSnpQykUser, getQyk, delQyk, addQyk, updateQyk, exportQyk,countQyk,detailExport } from "@/api/wx/qyk";
import { listQyx } from "@/api/wx/qyx";
import { listCouponInfo } from "@/api/ypp/couponInfo";

export default {
  name: "Qyk",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 权益卡表格数据
      qykList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        originalPrice: undefined,
        price: undefined,
        status: undefined,
        wxClientId: undefined
      },
      count:{

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        originalPrice: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        qyxIds: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
      },
      // 状态数据字典
      statusOptions: [],
      channelOptions: [
        {name:'用户购买',value:'0'},
        {name:'抽奖渠道',value:'1'},
      ],
      qyxList: [],
      qyxIdsList: [],
      qyxObj: [],
      buttonLoading:false,
      couponInfoList:[],
      userShow:false,
      userList:[]
    };
  },
  created() {
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    listQyx().then(response=>{
      this.qyxList = response.rows;
      let qyxObj = {};
      response.rows.forEach(e=>{
        qyxObj[e.id] = e.name;
      });
      this.qyxObj = qyxObj;
    });
    countQyk().then(res=>{
      if(res.code === 200){
        this.count  = res.data;
      }
    });
    this.getList();
    var list = [];
    var date = new Date();
    listCouponInfo({status:1,lyfs:0}).then(res=>{
      if(res.code == 200) {
        res.rows.forEach(function (value) {
          if(!value.yxts){
            var yxsj = new Date(value.yxsj);
            if (yxsj < date) {
              value.disabled = true;
            }
          }
          list.push(value);


        });
        this.couponInfoList = list;
      }
    })
  },
  methods: {
    showUser(row){
      var that = this;
      listSnpQykUser(row.id).then(res=>{
        if(res.code == 200){
          that.userList = res.rows;
          that.userShow = true;
        }
      })
    },
    /** 查询权益卡列表 */
    getList() {
      this.loading = true;
      listSnpQyk(this.queryParams).then(response => {
        this.qykList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        originalPrice: undefined,
        price: undefined,
        status: "0",
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        wxClientId: undefined,
        qyxIds: [],
        couponIds:[]
      };
      this.resetForm("form");
      this.qyxIdsList = [];
    },
    // 状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    channelFormat(row){
      let txt = '';
      this.channelOptions.forEach(e=>{
        if(row.channel == e.value){
          txt = e.name;
          return;
        }
      });
      return txt;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!=1;
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加权益卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let that =this ;
      this.reset();
      const id = row.id || this.ids;
      getQyk(id).then(response => {
        let qyxIds = [];
        let couponIds;
        let ids = [];
        response.data.qykMxList.forEach(e=>{
          qyxIds.push(e.qyxId)
        });
        if(response.data.couponIds){
          couponIds = response.data.couponIds.split(",");
          couponIds.map(function (i){
            ids.push(Number(i)) ;
          })
        }
        this.form = response.data;
        this.form.qyxIds = qyxIds;
        this.qyxIdsList = response.data.qykMxList;
        that.form.couponIds = ids;
        this.open = true;
        this.title = "修改权益卡";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      if(this.buttonLoading){
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.qykMxList = this.qyxIdsList;
          this.buttonLoading = true;
          this.loading = true;
          if(this.form.couponIds){
            this.form.couponIds = this.form.couponIds.join(",");
          }
          if (this.form.id != undefined) {
            updateQyk(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.buttonLoading = false;
              }
            });
          } else {
            addQyk(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.buttonLoading = false;
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除权益卡编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delQyk(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有权益卡数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportQyk(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleExportDetail() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有权益卡剩余次数数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return detailExport(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    },
    qyxIdsChange(vals){
      let obj = {};
      this.qyxIdsList.forEach(e=>{
        obj[e.qyxId] = e.num;
      });

      let arr = [];
      vals.forEach(e=>{
        arr.push({
          qyxId: e,
          qyxName: this.qyxObj[e],
          num: obj[e]
        })
      });
      this.qyxIdsList = arr;
    },
    couponIdsChange(vals){
      console.log(vals)

    },
  }
};
</script>
